package com.jh.paymentchannel.service.impl;

import cn.jh.common.core.json.JsonKt;
import cn.jh.common.exception.ServiceException;
import cn.jh.common.tools.Strings;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConstants;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayOpenAuthTokenAppQueryRequest;
import com.alipay.api.request.AlipayOpenAuthTokenAppRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppQueryResponse;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.google.common.collect.Maps;
import com.jh.paymentchannel.payment.alipay.AlipayConfig;
import com.jh.paymentchannel.pojo.AlipayAuthToken;
import com.jh.paymentchannel.pojo.WeixinServiceNo;
import com.jh.paymentchannel.repository.AlipayAuthTokenRepository;
import com.jh.paymentchannel.repository.WeixinServiceNoRepository;
import com.jh.paymentchannel.service.PassagewayConfigureService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;

@Service
public class PassagewayConfigureServiceImpl implements PassagewayConfigureService {

    @Autowired
    private WeixinServiceNoRepository weixinServiceNoRepository;

    @Autowired
    private AlipayAuthTokenRepository alipayAuthTokenRepository;

    @Autowired
    private AlipayConfig alipayConfig;

    @Override
    public WeixinServiceNo findWeixinServiceNo(String shopId) {
        return weixinServiceNoRepository.findByShopId(shopId);
    }

    /**
     * 查询微信配置信息
     * @param weixinServiceNo
     * @return
     */
    public WeixinServiceNo queryWeixinServiceNo(WeixinServiceNo weixinServiceNo) throws SQLException{
        return weixinServiceNoRepository.findByShopId(weixinServiceNo.getShopId());
    }

    /**
     * 保存微信配置信息
     * @param weixinServiceNo
     */
    @Transactional
    public WeixinServiceNo saveWeixinServiceNo(WeixinServiceNo weixinServiceNo) throws ServiceException {
        if (Strings.isNullOrEmpty(weixinServiceNo.getAppid())) {
            weixinServiceNo.setAppid(weixinServiceNo.getPartner());
        }
        String appid = weixinServiceNo.getAppid();
        WeixinServiceNo ws = weixinServiceNoRepository.findByAppId(appid);
        if (null != ws) {
            throw new ServiceException("微信子商户号已存在！");
        }
        return weixinServiceNoRepository.save(weixinServiceNo);
    }

    @Override
    public AlipayAuthToken findAlipayAuthToken(@NotNull String shopId) {
        return alipayAuthTokenRepository.findByShopId(shopId);
    }

    @Transactional
    @Override
    public AlipayAuthToken updateAuthToken(AlipayAuthToken updateToken) {
        return alipayAuthTokenRepository.saveAndFlush(updateToken);
    }

    @Transactional
    @Override
    public AlipayAuthToken alipayOpenAuthToken(String shopId, String appId, String appAuthCode) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getServerUrl(),
                alipayConfig.getAppId(), alipayConfig.getPrivateKey(), AlipayConstants.FORMAT_JSON,
                AlipayConstants.CHARSET_UTF8, alipayConfig.getAlipayPubKey(), "RSA2");
        // 获取授权token
        AlipayOpenAuthTokenAppRequest tokenAppRequest = new AlipayOpenAuthTokenAppRequest();
        Map<String, String> bizContent = Maps.newHashMap();
        bizContent.put("grant_type", "authorization_code");
        bizContent.put("code", appAuthCode);
        tokenAppRequest.setBizContent(JsonKt.toJSONString(bizContent));
        AlipayOpenAuthTokenAppResponse tokenAppResponse = alipayClient.execute(tokenAppRequest);
        if (!tokenAppResponse.isSuccess()) {
            throw new AlipayApiException(tokenAppResponse.getSubMsg());
        }
        // 初始化支付宝授权信息表
        AlipayAuthToken alipayAuthToken = alipayAuthTokenRepository.findByShopId(shopId);
        if (alipayAuthToken == null) {
            alipayAuthToken = AlipayAuthToken.create(shopId, appAuthCode, tokenAppResponse);
        } else {
            alipayAuthToken.update(appAuthCode, tokenAppResponse);
        }
        // 根据获得的授权token查询授权信息
        bizContent.clear();
        AlipayOpenAuthTokenAppQueryRequest tokenAppQueryRequest = new AlipayOpenAuthTokenAppQueryRequest();
        bizContent.put("app_auth_token", tokenAppResponse.getAppAuthToken());
        tokenAppQueryRequest.setBizContent(JsonKt.toJSONString(bizContent));
        AlipayOpenAuthTokenAppQueryResponse tokenAppQueryResponse = alipayClient.execute(tokenAppQueryRequest);
        if (!tokenAppQueryResponse.isSuccess()) {
            throw new AlipayApiException(tokenAppQueryResponse.getSubMsg());
        }
        if (Objects.equals(tokenAppQueryResponse.getStatus(), "valid")) {
            alipayAuthToken.setEnabled(true);
            alipayAuthToken.setAuthStartTime(tokenAppQueryResponse.getAuthStart());
            alipayAuthToken.setAuthEndTime(tokenAppQueryResponse.getAuthEnd());
        } else {
            alipayAuthToken.setEnabled(false);
        }
        alipayAuthTokenRepository.saveAndFlush(alipayAuthToken);
        return alipayAuthToken;
    }
}
